﻿using Microsoft.Win32;

namespace LegendHub.IO
{
    /// <summary>
    /// 写注册表创建文件关联
    /// </summary>
    public static class FileAssociation
    {
        /// <summary>
        /// 写注册表创建文件关联
        /// </summary>
        /// <param name="fileFormat">文件扩展名(.png ,.jpg...)</param>
        /// <param name="filePath">程序执行路径</param>
        /// <param name="iconPath">应用程序图标</param>
        /// <param name="companyName">公司名称</param>
        /// <param name="softName">软件名称</param>
        /// <returns>是否创建成功</returns>
        public static bool CreateFileAssociation(string fileFormat, string filePath, string iconPath, string companyName, string softName)
        {
            var isCreated = true;
            try
            {
                var key = Registry.ClassesRoot.CreateSubKey(companyName);
                if (key != null)
                {
                    key.SetValue("", softName);
                    //创建图标关联
                    var keyico = key.CreateSubKey("DefaultIcon");
                    if (keyico != null) keyico.SetValue("", iconPath + "");

                    //创建格式关联
                    key = key.CreateSubKey("Shell");

                    if (key != null)
                    {
                        key = key.CreateSubKey("Open");
                        if (key != null)
                        {
                            key = key.CreateSubKey("Command");
                            if (key != null) key.SetValue("", filePath + " \"%1\"");
                        }
                    }
                }

                key = Registry.ClassesRoot.CreateSubKey(fileFormat);
                if (key != null) key.SetValue("", companyName);
            }
            catch
            {
                isCreated = false;
            }
            return isCreated;
        }
    }
}